<template>
	<a-drawer
		class="app-drawer"
		v-model:visible="visible"
		:width="view && view.width ? view.width : 750"
		height="100%"
		:destroyOnClose="true"
		:placement="placement"
		:closable="closable"
		@close="handleClose"
	>
		<!-- 多语言 -->
		<a-config-provider :locale="getAntdLocale">
			<component
				:is="view && view.codeName"
				:context="context"
				:viewParams="props.viewParams"
				:name="view && view.codeName"
				openType="MODAL"
				@view-action="(name: string, action: IEvent<string>, data: IParam) => { handleViewAction(name, action, data); }"
				@view-init="(name: string, data: IViewAbility) => { handleViewInit(name, data); }"
				@view-destroy="(name: string, data: IParam) => { handleViewDestroy(name, data); }"
			/>
		</a-config-provider>
	</a-drawer>
</template>

<script setup lang="ts">
import {
	IEvent,
	IViewAbility,
	IOpenViewResult,
	IParam,
	ICustomDialogOptions,
} from '@/core';
import { useLocale } from '@/locales';
import { DrawerProps } from './drawer';
import { useViewActionStoreWithOut } from '@/store';

const visible = ref<boolean>(true);
const props = defineProps(DrawerProps);
const closable = computed(() => {
	return (
		Object.is(props.placement, 'top') || Object.is(props.placement, 'bottom')
	);
});

const emit = defineEmits(['drawer-action']);

let result: IOpenViewResult = { ok: true, data: [] };
const handleViewAction = (
	name: string,
	action: IEvent<string>,
	data: IParam
) => {
	if (Object.is(action, 'viewDataChange')) {
		if (data && Array.isArray(data) && data.length > 0) {
			result = { ok: true, data: JSON.parse(JSON.stringify(data)) };
		}
	} else if (
		Object.is(action, 'viewDataActive') ||
		Object.is(action, 'viewClose')
	) {
		if (data && Array.isArray(data) && data.length > 0) {
			result = { ok: true, data: JSON.parse(JSON.stringify(data)) };
			handleDrawerClose();
		} else if (Object.is(action, 'viewClose')) {
			handleDrawerClose();
		}
	}
};
const { getAntdLocale } = useLocale();
const handleViewInit = (name: string, data: IViewAbility) => {
	// todo
};

const handleViewDestroy = (name: string, data: IParam) => {
	handleDrawerClose();
};

const handleClose = () => {
	visible.value = true;
	handleDrawerClose();
};

// 处理抽屉关闭
const handleDrawerClose = () => {
	const { getStateByTag, removeAppViewsByTag } = useViewActionStoreWithOut();
	const closeModal = () => {
		visible.value = false;
		emit('drawer-action', result);
	};
	const state = getStateByTag(props.view.codeName);
	if (state) {
		const dialogOption: ICustomDialogOptions = App.getViewCloseHint(
			props.view.codeName
		);
		App.getDialogHelper().custom({
			...dialogOption,
			ok: () => {
				removeAppViewsByTag(props.view.codeName);
				closeModal();
			},
		});
	} else {
		closeModal();
	}
};
</script>
